package cn.xiaobai.v3;

import cn.xiaobai.http.Request;
import cn.xiaobai.http.Response;
import cn.xiaobai.utils.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai.v3
 * @ClassName HttpHandler3
 */
public class HttpHandler3 implements Runnable {

    static LoggerFactory.Logger log = LoggerFactory.getLogger(HttpHandler3.class);

    static TomcatFactory tomcatFactory = TomcatFactory.run();
    private Socket socket;

    private String body;

    public HttpHandler3(Socket socket) {
        this.socket = socket;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public void run() {
        try {
            // 1. 使用线程处理请求
            log.info("====== tomcat v3 监听 {} 端口, 当前线程名称: {}", socket.getPort(), Thread.currentThread().getName());

            // 接收到发送的数据
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String uri = request.getUri();
            MyServlet servlet = tomcatFactory.getServlet(uri);
            if (servlet != null) {
                response.setBody(body);
                servlet.service(request, response);
            } else {
                String body = "<body> 404 not found </body>";
                response.setCode(404);
                response.setBody(body);
                response.write();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
